<script setup lang="ts" name="ResetPasswordForm">
import { ref, reactive, computed, defineProps, defineEmits } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import type { ResetPasswordRequest } from '@/model/user-role-model'
import { resetPassword } from '@/request/user-role-api'

const props = defineProps<{
  visible: boolean
  userId: number | null
  userName: string
}>()

const emit = defineEmits<{
  (e: 'update:visible', visible: boolean): void
  (e: 'reset'): void
}>()

// 表单引用
const formRef = ref<FormInstance>()

// 重置模式：custom=自定义密码，default=默认密码
const resetMode = ref<'custom' | 'default'>('custom')

// 表单数据
const formData = reactive({
  new_password: '',
  confirm_password: ''
})

// 计算属性：当前有效用户ID
const currentUserId = computed(() => props.userId)

// 表单校验规则
const rules = reactive<FormRules>({
  new_password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码不能少于 6 个字符', trigger: 'blur' }
  ],
  confirm_password: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (value !== formData.new_password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

// 重置为默认密码
const resetToDefaultPassword = async () => {
  const userId = currentUserId.value
  if (userId === null) {
    ElMessage.error('无效的用户ID')
    return
  }
  
  try {
    // 调用不带参数的resetPassword，重置为默认密码
    const res = await resetPassword(userId)
    
    if (res.code === 0) {
      ElMessage.success('密码已重置为默认密码：123456')
      closeDialog()
      emit('reset')
    } else {
      ElMessage.error(res.errorMsg || '密码重置失败')
    }
  } catch (error) {
    console.error('重置密码出错：', error)
    ElMessage.error('密码重置失败')
  }
}

// 提交自定义密码表单
const submitCustomPasswordForm = async () => {
  if (!formRef.value) return
  const userId = currentUserId.value
  if (userId === null) {
    ElMessage.error('无效的用户ID')
    return
  }
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 创建密码重置请求数据
        const resetData: ResetPasswordRequest = {
          new_password: formData.new_password,
          confirm_password: formData.confirm_password
        }
        
        // 调用resetPassword函数，重置为自定义密码
        const res = await resetPassword(userId, resetData)
        
        if (res.code === 0) {
          ElMessage.success('密码重置成功')
          closeDialog()
          emit('reset')
        } else {
          ElMessage.error(res.errorMsg || '密码重置失败')
        }
      } catch (error) {
        console.error('重置密码出错：', error)
        ElMessage.error('密码重置失败')
      }
    }
  })
}

// 处理重置密码
const handleResetPassword = () => {
  if (resetMode.value === 'default') {
    // 确认是否重置为默认密码
    ElMessageBox.confirm(
      `确定要将用户 ${props.userName} 的密码重置为默认密码(123456)吗？`, 
      '重置密码确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(() => {
      resetToDefaultPassword()
    }).catch(() => {
      // 用户取消操作，不做任何处理
    })
  } else {
    // 自定义密码模式
    submitCustomPasswordForm()
  }
}

// 关闭弹窗
const closeDialog = () => {
  emit('update:visible', false)
  if (formRef.value) {
    formRef.value.resetFields()
  }
  formData.new_password = ''
  formData.confirm_password = ''
  resetMode.value = 'custom' // 重置为自定义密码模式
}
</script>

<template>
  <el-dialog
    title="重置密码"
    :model-value="visible"
    @update:model-value="(val) => emit('update:visible', val)"
    :close-on-click-modal="false"
    width="500px"
    @closed="closeDialog"
  >
    <div class="mb-4 text-gray-600">
      您正在为用户 <span class="font-bold text-primary">{{ userName }}</span> 重置密码
    </div>
    
    <!-- 重置密码模式选择 -->
    <div class="mb-4">
      <el-radio-group v-model="resetMode">
        <el-radio label="custom">自定义密码</el-radio>
        <el-radio label="default">重置为默认密码 (123456)</el-radio>
      </el-radio-group>
    </div>
    
    <!-- 自定义密码表单 -->
    <el-form
      v-if="resetMode === 'custom'"
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
      label-position="right"
    >
      <el-form-item label="新密码" prop="new_password">
        <el-input 
          v-model="formData.new_password" 
          type="password" 
          placeholder="请输入新密码"
          show-password
        />
      </el-form-item>
      
      <el-form-item label="确认新密码" prop="confirm_password">
        <el-input 
          v-model="formData.confirm_password" 
          type="password" 
          placeholder="请再次输入新密码"
          show-password
        />
      </el-form-item>
    </el-form>
    
    <!-- 默认密码提示 -->
    <div v-if="resetMode === 'default'" class="mb-4 p-4 bg-yellow-50 border border-yellow-200 rounded-md text-yellow-700">
      <p>点击确认后，系统将自动重置用户密码为默认密码：<strong>123456</strong></p>
      <p class="mt-2 text-sm">请提醒用户登录后及时修改密码</p>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="handleResetPassword">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>
